package fun.tan90.easy.binlog.plugin.webhook.config;


import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.webhook.listener.WebhookEventProcessor;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.webhook.model.WebhookParams;
import fun.tan90.easy.binlog.plugin.webhook.service.impl.WebhookPluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class WebhookPluginAutoConfiguration {

    public WebhookPluginAutoConfiguration() {
        log.info("init WebhookPlugin");
    }

    @Bean
    public WebhookParamsCacheLoader webhookParamsCacheLoader() {
        return new WebhookParamsCacheLoader();
    }

    @Bean
    public LoadingCache<String, WebhookParams> webhookParamsCache(WebhookParamsCacheLoader webhookParamsCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.WEBHOOK.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(webhookParamsCacheLoader);
    }

    @Bean
    public WebhookEventProcessor webhookEventProcessor(LoadingCache<String, WebhookParams> webhookParamsCache) {
        return new WebhookEventProcessor(webhookParamsCache);
    }

    @Bean(name = "webhook")
    public PluginService webhookPluginService() {
        return new WebhookPluginService();
    }
}
